<template>
  <div class="portfolio-detial-page">
    <div class="portfolio-profile">
      <div class="tg-profile van-hairline--bottom">
        <van-image class="avatar" lazy-load  width="25px" height="25px" round :src="tgInfo.avatar"
          @click.native.stop="$router.push(`/adviser/detail/${tgInfo.id}/`)"
        ></van-image>
        <p class="van-ellipsis">{{tgInfo.name}}</p>
        <div class="tag-list">
          <span class="tag" v-if="tgInfo.type === 1">金牌投资顾问</span>
          <span class="tag" v-else-if="tgInfo.type === 2">投资顾问</span>
        </div>
      </div>
      <h1>{{relation.totalProfitRate | numberFormat('0.00%')}}</h1>
      <span>总收益</span>
      <van-row type="flex" justify="space-around" style="margin: 15px 0;">
        <van-col span="8">
          <p>{{relation.weekProfitRate | numberFormat('0.00%')}}</p>
          <span>周收益</span>
        </van-col>
        <van-col span="8">
          <p>{{relation.monthProfitRate | numberFormat('0.00%')}}</p>
          <span>月收益</span>
        </van-col>
        <van-col span="8">
          <p>{{relation.seasonProfitRate | numberFormat('0.00%')}}</p>
          <span>近三月收益</span>
        </van-col>
      </van-row>
      <van-row type="flex" justify="space-around" style="margin: 15px 0;">
        <van-col span="8">
          <p>{{relation.currentNetValue | numberFormat('0.000')}}</p>
          <span>组合净值</span>
        </van-col>
        <van-col span="8">
          <p>{{relation.maxRetracement | numberFormat('0.00%')}}</p>
          <div class="icon-wrapper" @click="showDialog('组合建立以来经历过的一次最大亏损比率。最大亏损越高，说明该组合风险越高。', '最大回撤')">
            <span>最大回撤</span>
            <van-icon color="rgba(255,255,255,0.6)" size="14" name="question" />
          </div>
        </van-col>
        <van-col span="8">
          <p>{{relation.successRate | numberFormat('0.00%')}}</p>
          <div class="icon-wrapper" @click="showDialog('获利了结的股票数/完整交易股票数。胜率越高，说明该组合盈利的可能性越高。', '胜率')">
            <span>胜率</span>
          </div>
        </van-col>
      </van-row>
    </div>
    <div class="chart-area">
      <van-tabs type="card" :swipe-threshold="5" @click="changeTime">
        <van-tab title="1月"></van-tab>
        <van-tab title="3月"></van-tab>
        <van-tab title="半年"></van-tab>
        <van-tab title="1年"></van-tab>
        <van-tab title="3年"></van-tab>
      </van-tabs>
      <line-chart ref="line-chart"/>
    </div>
    <div class="tab-area">
      <van-tabs v-model="active" @rendered="onRendered" sticky swipeable line-width="20px" line-height="4px">
        <van-tab title="当前持仓">
          <div class="tab-content">
            <bar-chart ref="bar-chart"/>
            <div class="table-wrapper">
              <table>
                <thead>
                  <tr>
                    <th class="text-left">证券代码</th>
                    <th class="text-center">现价/成本</th>
                    <th class="text-center">仓位</th>
                    <th class="text-right">持仓盈亏</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="hold in holdList" :key="hold.secuCode">
                    <td class="text-left">
                      <p>{{hold.secuName}}</p>
                      <span>{{hold.secuCode}}</span>
                    </td>
                    <td class="text-center" v-if="hold.stockType === 0">
                      <p>{{hold.currentPrice | numberFormat('0.00')}}</p>
                      <span>{{hold.costPrice | numberFormat('0.00')}}</span>
                    </td>
                    <td class="text-center" v-if="hold.stockType === 1">
                      <p>{{hold.currentPrice | numberFormat('0.000')}}</p>
                      <span>{{hold.costPrice | numberFormat('0.000')}}</span>
                    </td>
                    <td class="text-center">
                      <p>{{((hold.mktQty * hold.currentPrice) / capital.sumAst) | numberFormat('0.00%')}}</p>
                    </td>
                    <td class="text-right">
                      <p :class="hold.floatProfit | numberColor">{{hold.floatProfit | numberFormat('0.00')}}</p>
                      <span :class="((hold.currentPrice - hold.costPrice) / hold.costPrice) | numberColor">
                        {{ ((hold.currentPrice - hold.costPrice) / hold.costPrice) | numberFormat('0.00%') }}
                      </span>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </van-tab>
        <van-tab title="调仓记录">
          <div class="tab-content">
            <div class="table-wrapper">
              <p class="tips" v-if="transferRecord.length">查看调仓记录请先订阅</p>
              <table>
                <thead>
                  <tr>
                    <th class="text-left">时间</th>
                    <th class="text-center">方向</th>
                    <th class="text-center">股票名称</th>
                    <th class="text-right">成交价</th>
                  </tr>
                </thead>
                <tbody v-for="(stocks, index) in transferRecord" :key="index">
                  <tr>
                    <td colspan="4" class="date">
                      <span class="time">{{stocks[0].orderDate.slice(0, 8).splice(4, 0, '/').splice(7, 0, '/')}}</span>
                    </td>
                  </tr>
                  <tr v-for="stock in stocks" :key="stock.secuCode + stock.orderDate">
                    <td class="text-left">
                      <p>{{stock.orderDate.slice(8, 12).splice(2, 0, ":")}}</p>
                    </td>
                    <td class="text-center">
                      <span class="direction buy" v-if="stock.trdID === 0">买入</span>
                      <span class="direction sell" v-if="stock.trdID === 1">卖出</span>
                    </td>
                    <td class="text-center">
                      <div class="text-left" style="padding-left: 15px;">
                        <p>{{stock.secuName}}</p>
                        <!-- <span>{{stock.secuCode}}</span> -->
                      </div>
                    </td>
                    <td class="text-right" v-if="stock.stockType === '1'">
                      <p>{{stock.matchedPrice | numberFormat('0.000')}}</p>
                    </td>
                    <td class="text-right" v-else>
                      <p>{{stock.matchedPrice | numberFormat('0.00')}}</p>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <div class="text-center">
            <van-loading v-show="loading" type="spinner" size="16px">加载中...</van-loading>
          </div>
        </van-tab>
        <van-tab title="组合理念">
          <div class="tab-content concept">
            <p>{{portfolio.intro}}</p>
            <p>风险提示：本组合所展示的收益率等指标为历史模拟数据，不代表实际和将来的收益率，不构成收益承诺。客户需独立做出投资决策，风险自担。市场有风险，投资需谨慎。</p>
          </div>
        </van-tab>
      </van-tabs>
    </div>
    <div class="bottom-btn">
      <van-row>
        <van-col :span="18">
        <van-button @click.native="onLogin" round color="linear-gradient(to right, #ED7F31, #E8302E)" block >
          <span >立即订阅</span>
        </van-button>
        </van-col>
        <van-col :span="6" style="padding-left: 15px;">
          <van-button round class="share-btn" block @click="share">
            分享
          </van-button>
        </van-col>
      </van-row>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import { Tabs, Tab, Icon, Dialog, Loading, Button } from 'vant';
import LineChart from './components/LineChart';
import BarChart from './components/BarChart';
import { queryPortfolioDetailApp, queryBargainList, queryHisProfit } from '../../api/portfolio';
import dayjs from 'dayjs';
import isEmpty from 'lodash/isEmpty';
import { PERIOD_TYPE, ICON_RED_GREEN } from '../../constant';
import { closeWebView, shareLink } from '../../api/native';

export default {
  components: {
    [Tabs.name]: Tabs,
    [Tab.name]: Tab,
    [Icon.name]: Icon,
    [Loading.name]: Loading,
    [Button.name]: Button,
    LineChart,
    BarChart,
  },

  data() {
    return {
      active: 0,
      holdList: [],
      portfolio: {
        productGroup: {}
      },
      relation: {},
      capital: {},
      tgInfo: {
        avatar: ''
      },
      transferRecord: [],
      loading: false,
      page: 1,
      size: 100,
      hasAuth: false,
      commissionTable: [],
      product: {
        products: []
      },
    }
  },

  mounted() {

    this.getProfitRate();
    this.$bus.$on('reachBottom', () => {
      if(this.active === 1) {
        this.reachBottom()
      }
    });
  },

  beforeDestroy() {
    this.$bus.$off('reachBottom');
  },

  computed: {
    ...mapGetters(['isLogin', 'isFundLogin']),
  },

  methods: {
    ...mapActions(['login', 'fundLogin']),

    async queryPortfolioDetailApp() {
      try {
        this.$refs['bar-chart'].showLoading();
        const data = await queryPortfolioDetailApp(this.$route.params.id);
        this.holdList = data.holdList;
        this.portfolio = data.portfolio;
        this.relation = data.relation;
        this.tgInfo = data.tgInfo;
        this.capital = data.capital;

        if(this.portfolio.status === 4) {
          Dialog.alert({
            message: '此组合已下架'
          }).then(() => closeWebView())
        }

        this.$setTitle(this.portfolio.name);

        const barData = data.indusPosList.map(stock => {
          return {
            name: stock.name,
            value: (stock.rate * 100).toFixed(2),
          };
        });

        this.$refs['bar-chart'].setOption({
          legend: {
            formatter: name => `${name}: ${barData.find(item => item.name === name).value}%`,
              data: barData.map(item => {
                return Object.assign(item, {
                  icon: 'circle',
                  textStyle: {
                    color: '#666'
                  }
                });
              })
            },
            series: [{ data: barData }]
        });

      } catch (error) {
        console.error(error);
      } finally {
        this.$refs['bar-chart'].hideLoading();
      }
    },

    async queryBargainList() {
      try {
        this.loading = true;
        const data = await queryBargainList(this.$route.params.id, {
          offset: (this.page - 1) * this.size,
          size: this.size,
        });
        this.transferRecord = data.list;
      } catch (error) {
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    async getProfitRate(duration = 1) {
      try {
        this.$refs['line-chart'].showLoading();
        const res = await queryHisProfit(this.$route.params.id, {
          beginDate: dayjs().subtract(duration, 'month').format('YYYYMMDD'),
          endDate: dayjs().format('YYYYMMDD')
        });
        this.$refs['line-chart'].setOption({
          xAxis: { data: res.list.map(item => item.date.slice(4).splice(2, 0, ".")) },
          series: [
            {
              data: res.list.map(item => Number(item.profitRate * 100) || 0) ,
              markPoint: {
                data: res.list.filter(item => item.tradeFlag).map(item => {
                  const color = ['', '#f8373f', '#1db44a']
                  return {
                    yAxis: Number(item.profitRate * 100),
                    xAxis: item.date.slice(4).splice(2, 0, "."),
                    symbol: item.tradeFlag === 3 ? `image://${ICON_RED_GREEN}` : 'circle',
                    symbolSize: 7,
                    itemStyle: {
                      color: color[item.tradeFlag]
                    }
                  };
                }),
              }
            },
            { data: res.list.map(item => Number(item.hs300ProfitRate * 100) || 0) },
          ]
        });

      } catch (error) {
        console.error(error);
      } finally {
        this.$refs['line-chart'].hideLoading();
      }
    },

    onRendered(name, title) {
      if(name === 0) {
        this.queryPortfolioDetailApp();
      } else if(name === 1) {
        this.queryBargainList();
      }
    },

    showDialog(message, title) {
      Dialog({
        message,
        title,
        confirmButtonText: '知道了'
      })
    },

    async reachBottom() {
      try {
        this.loading = true;
        ++this.page;
        const data = await queryBargainList(this.$route.params.id, {
          offset: (this.page - 1) * this.size,
          size: this.size,
        });
        this.transferRecord = this.transferRecord.concat(data.list);
      } catch (error) {
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    changeTime(name, title) {
      switch(name) {
        case 0:
          this.getProfitRate(1); // 1月
        case 1:
          this.getProfitRate(3); // 1月
        case 2:
          this.getProfitRate(6); // 1月
        case 3:
          this.getProfitRate(12); // 1月
        case 4:
          this.getProfitRate(36); // 1月
      }
    },

    share() {
      shareLink({
        url: location.href,
        title: this.portfolio.name,
        message: this.portfolio.intro
      })
    },

    /* 登录 */
    onLogin(){
      console.log(1);
      if(!this.isLogin){
        return this.login()
      }
    }
  },

}
</script>

<style lang="less">
.portfolio-detial-page {
  .portfolio-profile {
    background-image: url('../../assets/bg-portfolio.png');
    color: #fff;
    text-align: center;
    padding-bottom: 3px;
    background-size: cover;

    h1 {
      font-size: 24px;
    }

    span {
      color: rgba(255, 255, 255, 0.6);
      font-size: 13px;
    }

    .icon-wrapper {
      * {
        display: inline-block;
        vertical-align: middle;
      }

      span {
        margin-right: 2px;
      }
    }
  }

  .tg-profile {
    display: flex;
    align-items: center;
    padding: 10px 0;
    margin: 0 15px 20px 15px;

    span {
      font-size: 12px;
    }

    p {
      font-size: 16px;
      margin-left: 5px;
    }

    .avatar {
      border: 1px solid #fff;
    }

    .tag-list {
      flex: 1;
      text-align: right;

      .tag {
        border: 1px solid #fff;
        padding: 1px 3px;
        border-radius: 2px;
        color: #fff;

        &:not(:last-child) {
          margin-right: 5px;
        }
      }
    }

    .tg-info {
      margin-left: 15px;
    }

    .icon-arrow {
      flex: 1;
      text-align: right;
    }
  }

  .van-tab__text {
    font-size: 16px;
  }

  .chart-area {
    padding: 20px 0;
    background-color: #fff;
    margin: 10px 0;
  }

  .van-tabs__nav--card .van-tab {
    color: #9d9ea7;
  }

  .van-tabs__nav--card .van-tab.van-tab--active {
    color: #eb4339;
    background-color: #fdecec;
  }

  .tab-content {
    .table-wrapper .tips {
      display: none;
    }

    &.no-auth {
      margin-bottom: 80px;

      tbody {
        filter: url(../../assets/blur.svg#blur); /* FireFox, Chrome, Opera */

        -webkit-filter: blur(10px); /* Chrome, Opera */
          -moz-filter: blur(10px);
            -ms-filter: blur(10px);
                filter: blur(10px);

        filter: progid:DXImageTransform.Microsoft.Blur(PixelRadius=10, MakeShadow=false); /* IE6~IE9 */
      }


      .table-wrapper {
        position: relative;

        .tips {
          display: block;
          font-size: 16px;
          color: #5e616b;
          position: absolute;
          left: 50%;
          top: 60%;
          transform: translateX(-50%);
          z-index: 2;
        }
      }
    }

    table {
      width: 100%;
      background: #fff;
      font-size: 16px;
      color: #5e616b;

      thead, tbody {
        width: 100%;
      }

      th {
        font-weight: 400;
        padding: 8px;
      }
    }

    .time {
      color: #4C7AFF;
      font-size: 14px;
    }

    .date {
      background-color: #f5f6f6;
      padding: 5px 15px;

      span {
        color: #2b313d !important;
      }
    }

    .direction {
      font-size: 16px;
      display: inline-block;
      line-height: 25px;

      &.buy {
        color: #ff3a3b;
      }

      &.sell {
        color: #2baf95;
      }
    }

    &.concept {
      background-color: #fff;

      p {
        padding: 15px;

        &:first-child {
           color: #121D32;
           font-size: 16px;
        }

        &:last-child {
           color: #9d9ea7;
           font-size: 13px;
           line-height: 1.45;
        }
      }
    }
  }

  .bottom-btn {
    background-color: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    z-index: 99;

    .share-btn {
      color: #5e616b;
      border-color: #5e616b;
    }
  }
}
</style>
